package com.ice.delay.task.core.config;

import com.ice.delay.task.controller.LoginController;
import com.ice.delay.task.core.constant.ServerErrorCode;
import com.ice.framework.common.exception.BusinessException;
import org.springframework.util.MimeType;
import org.springframework.util.MimeTypeUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * 权限检验，传入请求session没有包含信息，则跳转到登录
 * @Author wangwei
 * @Date 2023/11/15
 */
public class AuthInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        Object attribute = session.getAttribute(LoginController.LOGIN_USER);
        if (attribute == null) {
            String contentType = request.getHeader("Accept");
            List<MimeType> mimeTypes = MimeTypeUtils.parseMimeTypes(contentType);
            if (mimeTypes.contains(MimeTypeUtils.APPLICATION_JSON)) {
                throw new BusinessException(ServerErrorCode.USER_CERTIFICATION);
            } else {
                response.sendRedirect("toLogin");
            }
            return false;
        } else {
            return true;
        }
    }

}
